package org.streets.database.internal;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.streets.database.RecordHandlerManager;
import org.streets.database.SQLConnection;
import org.streets.database.SQLConnectionManager;
import org.streets.database.SQLNestedException;
import org.streets.database.SQLTransaction;
import org.streets.database.dialect.Dialect;

/**
 * 本实现仅适用于符合STREETS开发规范的程序中(具备Tapestry-ioc及wicket支持)
 * 在tapestry-ioc中所有的对象都是自动Proxy的
 * 连接关闭使用tapestry-ioc的Thread监听器 对象获取从HiveRegistry中获取
 * 如果通用程序使用 org.streets.database.ConnectionManager
 * @author dzb
 *
 */
public class SQLConnectionManagerImpl implements SQLConnectionManager {
		
	private final SQLConnection connection;
	
	private SQLTransaction transaction;
	
	public SQLConnectionManagerImpl(DataSource ds, Dialect dialect) {
		if (ds == null) 
			throw new SQLNestedException("Can not find any avalible DataSource configuration.");
		try {
			connection = new SQLConnectionImpl(ds.getConnection(), dialect);
		} catch (SQLException e) {
			throw new SQLNestedException("Cannot fetch an active Connection from datasource", e);
		}
	}
	
	public SQLConnectionManagerImpl(DataSource ds, Dialect dialect, RecordHandlerManager handlerManager) {
		if (ds == null) 
			throw new SQLNestedException("Can not find any avalible DataSource configuration.");
		try {
			connection = new SQLConnectionImpl(ds.getConnection(), dialect, handlerManager);
		} catch (SQLException e) {
			throw new SQLNestedException("Cannot fetch an active Connection from datasource", e);
		}		
	}
    
	public void begin() {
        transaction = connection.beginTransaction();
    }
	
	public void abort() {
		if (transaction != null) {
			transaction.rollback();
		}
	}

	public void commit() {
		if (transaction != null) {
			transaction.commit();
		}
	}

	public SQLConnection getConnection() {
		return connection;
	}
		
	public void clean() {
		// 若还在事务中 就先回滚
		if (connection.isConnectionInTransaction()) {
			transaction.rollback();
		}
		connection.close();
	}
}
